<?php

/**
 * @author Immanuel Bauer | 0626117
 */
class User {
	
	/** 
	 * @var int 
	 */
	private $id;
	
	/** 
	 * @var string
	 */
	private $loginName;
	
	/**
	 *  @var string
	 */
	private $password;
	
	/** 
	 *	@var string 
	 */
	private $firstName;
	
	/** 
	 * @var string
	 */
	private $lastName;
	
	/** 
	 * @var string
	 */
	private $email;
	
	/** 
	 * @var string
	 */
	private $group;
	
	/** 
	 * @var boolean
	 */
	private $online;
	
	/**
	 * 
	 * @param int $id
	 * @param string $loginName
	 * @param string $password
	 * @param string $firstName
	 * @param string $lastName
	 * @param string $email
	 * @param boolean $online
	 */
	function __construct($loginName, $password, $firstName, $lastName, $email, $group = 'user', $online = false) {
		$this->id = null;
		$this->loginName = $loginName;
		$this->password = $password;
		$this->firstName = $firstName;
		$this->lastName = $lastName;
		$this->email = $email;
		$this->group = $group;
		$this->online = $online;
	}
	
	/**
	 * Fetches the user data for the given id and returns an User object with the Users data.
	 * Returns null if the User doesn't exist.
	 * 
	 * @param int $id
	 * @return User
	 */
	public static function getUser($id){
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'users WHERE id = \''.mysql_real_escape_string($id).'\';');
		$row = mysql_fetch_assoc($qry);
		if($row){
			$user = new User($row['login_name'], $row['password'], $row['first_name'], $row['last_name'], $row['email'], $row['group'], $row['online']);
			$user->setID($id);
			return $user;
		} else {
			return null;
		}
	}
	
	/**
	 * Fetches the user data for the given name and returns an User object with the Users data.
	 * Returns null if the User doesn't exist.
	 * 
	 * @param string $name
	 * @return User
	 */
	public static function getUserByName($name){
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'users WHERE login_name = \''.mysql_real_escape_string($name).'\';');
		$row = mysql_fetch_assoc($qry);
		if($row){
			$user = new User($row['login_name'], $row['password'], $row['first_name'], $row['last_name'], $row['email'], $row['group'], $row['online']);
			$user->setID($row['id']);
			return $user;
		} else {
			return null;
		}
	}
		
	/**
	 * Fetches the users matching the given parameters
	 * 
	 * @param int $listID
	 * @param int $todoID
	 * @return array<User>
	 */
	public static function getUsers($listID = null, $todoID = null, $from = 0, $rows = 30, $sort = 'n', $order = 'asc'){
		
		$where = '';
		if(!is_null($todoID)){
			$where .= '(tu.todo = \''.mysql_real_escape_string($todoID).'\') ';
		}
		if(!is_null($listID)){
			if($where != '') $where .= 'AND ';
			$where .= 'su.list = \''.mysql_real_escape_string($listID).'\'';
		}
		
		switch($sort){
			case 'n': $sort = 'u.login_name'; break;
			case 'fN': $sort = 'u.first_name'; break;
			case 'lN': $sort = 'u.last_name'; break;
			default: $sort = 'u.login_name'; break;
		}
		
		switch($order){
			case 'asc': $order = 'ASC'; break;
			case 'desc': $order = 'DESC'; break;
			case 'a': $order = 'ASC'; break;
			case 'd': $order = 'DESC'; break;
			default: $order = 'DESC'; break;
		}
		
		if($where != '') $where = 'WHERE '.$where;
		
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'users AS u LEFT JOIN '.TABLE_PREFIX.'share_list_user AS su ON su.user = u.id LEFT JOIN '.TABLE_PREFIX.'todo_user AS tu ON tu.user = u.id '.$where.' GROUP BY u.id ORDER BY '.$sort.' '.$order.' LIMIT '.mysql_real_escape_string($from).','.mysql_real_escape_string($rows).';');
		$u = array();
		while($row = mysql_fetch_assoc($qry)){
			$user = new User($row['login_name'], $row['password'], $row['first_name'], $row['last_name'], $row['email'], $row['group'], $row['online']);
			$user->setID($row['id']);
			array_push($u, $user);
		}
		return $u;
	}
	
	/**
	 * Fetches the count of users matching the given parameters
	 * 
	 * @param int $listID
	 * @param int $todoID
	 * @return int
	 */
	public static function getUserCount($listID = null, $todoID = null){
		
		$where = '';
		if(!is_null($todoID)){
			$where .= '(tu.todo = \''.mysql_real_escape_string($todoID).'\') ';
		}
		if(!is_null($listID)){
			if($where != '') $where .= 'AND ';
			$where .= 'su.list = \''.mysql_real_escape_string($listID).'\'';
		}
		
		if($where != '') $where = 'WHERE '.$where;

		$count = mysql_fetch_array(mysql_query('SELECT count(DISTINCT u.id) FROM '.TABLE_PREFIX.'users AS u LEFT JOIN '.TABLE_PREFIX.'share_list_user AS su ON su.user = u.id LEFT JOIN '.TABLE_PREFIX.'todo_user AS tu ON tu.user = u.id '.$where.';'));
		
		return (int)$count[0];
	}
	
	/**
	 * Fetches the users linked with the given Todo id and returns them in an array containg two subarrays under the keys 'users' and 'roles'. The first one contains an array of User objects, the latter an array of string stating the role
	 * 
	 * @param int $todoID
	 * @return array ['users'] => array(User), ['roles'] => array(string)
	 */
	public static function getUsersLinkedToTodo($todoID){
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'users AS u JOIN '.TABLE_PREFIX.'todo_user AS tu ON u.id = tu.user WHERE tu.todo = \''.mysql_real_escape_string($todoID).'\';');
		$u = array();
		$r = array();
		while($row = mysql_fetch_assoc($qry)){
			$user = new User($row['login_name'], $row['password'], $row['first_name'], $row['last_name'], $row['email'], $row['group'], $row['online']);
			$user->setID($row['id']);
			array_push($u, $user);
			array_push($r, $row['role']);
		}
		return array('users' => $u, 'roles' => $r);
	}
	
	/**
	 * Fetches the users linked with the given TodoList id and returns them in an array
	 * 
	 * @param int $listID
	 * @return array(User)
	 */
	public static function getUsersLinkedToList($listID){
		$qry = mysql_query('SELECT * FROM '.TABLE_PREFIX.'users AS u JOIN '.TABLE_PREFIX.'share_list_user AS su ON u.id = su.user WHERE su.list = \''.mysql_real_escape_string($listID).'\';');
		$u = array();
		while($row = mysql_fetch_assoc($qry)){
			$user = new User($row['login_name'], $row['password'], $row['first_name'], $row['last_name'], $row['email'], $row['group'], $row['online']);
			$user->setID($row['id']);
			array_push($u, $user);
		}
		return $u;
	}

	/**
	 * Checks if the given login credentails are valid.
	 * 
	 * @param string $loginName
	 * @param string $password
	 * 
	 * @return boolean
	 */
	public static function checkLogin($loginName, $password){
		$qry = mysql_query('SELECT password FROM '.TABLE_PREFIX.'users WHERE login_name = BINARY \''.mysql_real_escape_string($loginName).'\';');
		$user = mysql_fetch_assoc($qry);
		if($user && $user['password'] == $password){
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Saves the current state of the model object into the database
	 * @return boolean true if save was successfull
	 */
	public function saveToDB(){
		if(is_null($this->id)){
			//insert
			$qry = mysql_query('INSERT INTO '.TABLE_PREFIX.'users (`id`, `login_name`, `password`, `first_name`, `last_name`, `email`, `online`, `group`) VALUES (
				\'\',
				\''.mysql_real_escape_string($this->loginName).'\',
				\''.mysql_real_escape_string($this->password).'\',
				\''.mysql_real_escape_string($this->firstName).'\',
				\''.mysql_real_escape_string($this->lastName).'\',
				\''.mysql_real_escape_string($this->email).'\',
				\''.mysql_real_escape_string($this->online).'\',
				\''.mysql_real_escape_string($this->group).'\'
			);');
			if($qry){
				$qry = mysql_query('SELECT id FROM '.TABLE_PREFIX.'users WHERE login_name = \''.mysql_real_escape_string($this->loginName).'\';');
				$row = mysql_fetch_assoc($qry);
				if(isset($row['id'])){
					$this->id = (int)$row['id'];
					return true;
				} else{
					return false;
				}
			} else {
				return false;
			}
		} else {
			//update
			$qry = mysql_query('UPDATE `'.TABLE_PREFIX.'users` SET 
				`login_name` = \''.mysql_real_escape_string($this->loginName).'\',
				`password` = \''.mysql_real_escape_string($this->password).'\',
				`first_name` = \''.mysql_real_escape_string($this->firstName).'\',
				`last_name` = \''.mysql_real_escape_string($this->lastName).'\',
				`email` = \''.mysql_real_escape_string($this->email).'\',
				`online` = \''.mysql_real_escape_string($this->online).'\',
				`group` = \''.mysql_real_escape_string($this->group).'\' 
			WHERE `id` = \''.mysql_real_escape_string($this->id).'\';');
			return $qry;
		}
	}
	
	/**
	 * Removes the model object's corresponding row in the database and returns true if successfull.
	 * @return boolean
	 */
	public function removeFromDB(){
		if(!is_null($this->id)){
			return mysql_query('DELETE FROM '.TABLE_PREFIX.'users WHERE id = \''.mysql_real_escape_string($this->id).'\';');
		} else {
			return true;
		}
	}
	
/* ####### GETTER ####### */
	
	/**
	 * The User's id
	 * @return int
	 */
	public function getID(){
		return $this->id;	
	}
	
	/**
	 * The User's login name
	 * @return string
	 */
	public function getLoginName(){
		return $this->loginName;	
	}
	
	/**
	 * The User's first name
	 * @return string
	 */
	public function getFirstName(){
		return $this->firstName;	
	}
	
	/**
	 * The User's last name
	 * @return string
	 */
	public function getLastName(){
		return $this->lastName;	
	}
	
	/**
	 * The User's email
	 * @return string
	 */
	public function getEmail(){
		return $this->email;	
	}
	
	/**
	 * The User's group
	 * @return string
	 */
	public function getGroup(){
		return $this->group;	
	}
	
	/**
	 * The User's online status
	 * @return boolean
	 */
	public function isOnline(){
		return $this->online;	
	}

	/**
	 * The User's password
	 * @return string
	 */
	public function getPassword(){
		return $this->password;	
	}
	
/* ####### SETTER ####### */
	
	/**
	 * Sets the User's id
	 * @param int $id;
	 */
	private function setID($id){
		$this->id = (int)$id;	
	}
	
	/**
	 * Sets the User's login name
	 * @param string $loginName
	 */
	public function setLoginName($loginName){
		$this->loginName = $loginName;	
	}
	
	/**
	 * Sets the User's first name
	 * @param string $firstName
	 */
	public function setFirstName($firstName){
		$this->firstName = $firstName;	
	}
	
	/**
	 * Sets the User's last name
	 * @param string $lastName
	 */
	public function setLastName($lastName){
		$this->lastName = $lastName;	
	}
	
	/**
	 * Sets the User's email
	 * @param string $email
	 */
	public function setEmail($email){
		$this->email = $email;	
	}
	
	/**
	 * Sets the User's group
	 * @param string $group
	 */
	public function setGroup($group){
		$this->group = $group;	
	}
	
	/**
	 * Sets the User's online status
	 * @param boolean $online
	 */
	public function setOnline($online){
		$this->online = $online;	
	}
	
	/**
	 * Sets the User's password
	 * @param string $password
	 */
	public function setPassword($password){
		$this->password = $password;	
	}
	
}

?>